
<template>
    <div class="cart">
        <div class="cart-header">
            <h1>购物车</h1>
            <p v-if="cartStore.itemCount > 0">共 {{ cartStore.itemCount }} 件商品</p>
        </div>

        <!-- 加载状态 -->
        <div v-if="cartStore.loading" class="loading-spinner">
            <LoadingSpinner />
        </div>

        <!-- 购物车为空 -->
        <EmptyState v-else-if="cartStore.itemCount === 0" title="购物车为空" description="快去挑选心仪的商品吧" :icon="ShoppingCart">
            <template #actions>
                <el-button type="primary" @click="$router.push('/products')">
                    去购物
                </el-button>
            </template>
        </EmptyState>

        <!-- 购物车有商品 -->
        <div v-else class="cart-content">
            <el-card class="cart-list">
                <div class="cart-header-actions">
                    <el-checkbox v-model="isAllSelected" @change="cartStore.toggleAllSelection()">
                        全选
                    </el-checkbox>
                    <el-button type="danger" size="small" @click="handleClearSelected"
                        :disabled="cartStore.selectedCount === 0">
                        删除选中
                    </el-button>
                </div>

                <div class="cart-items">
                    <div v-for="item in cartStore.items" :key="item.productId" class="cart-item">
                        <el-checkbox v-model="item.selected" @change="cartStore.toggleSelection(item.productId)" />

                        <img :src="item.imageUrl" :alt="item.name" class="item-image" />

                        <div class="item-info">
                            <h3 class="item-name">{{ item.name }}</h3>
                            <div class="item-points">{{ item.points }} 积分</div>
                        </div>

                        <div class="item-quantity">
                            <el-input-number :model-value="item.quantity" :min="1" :max="item.stock"
                                @change="(quantity: number) => cartStore.updateQuantity(item.productId, quantity)" size="small" />
                        </div>

                        <div class="item-total">
                            <div class="total-points">{{ item.points * item.quantity }} 积分</div>
                        </div>

                        <div class="item-actions">
                            <el-button type="danger" size="small" @click="cartStore.removeFromCart(item.productId)">
                                删除
                            </el-button>
                        </div>
                    </div>
                </div>
            </el-card>

            <!-- 结算区域 -->
            <el-card class="cart-summary" v-if="cartStore.selectedCount > 0">
                <div class="summary-content">
                    <div class="summary-info">
                        <p>已选择 {{ cartStore.selectedCount }} 件商品</p>
                        <p>总计：<span class="total-points">{{ cartStore.totalPoints }} 积分</span></p>
                    </div>
                    <div class="summary-actions">
                        <el-button type="primary" size="large" @click="handleCheckout" :loading="checkingOut">
                            结算 ({{ cartStore.totalPoints }} 积分)
                        </el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createOrder } from '@/api/modules/order'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import EmptyState from '@/components/base/EmptyState.vue'
import LoadingSpinner from '@/components/base/LoadingSpinner.vue'
import { ShoppingCart } from '@element-plus/icons-vue'

const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

const checkingOut = ref(false)

// 计算属性，用于 v-model 绑定
const isAllSelected = computed({
    get: () => cartStore.isAllSelected,
    set: (value) => {
        // The action will handle the logic
        cartStore.toggleAllSelection()
    }
})

onMounted(() => {
    cartStore.fetchCart()
})

// 清空选中的商品
const handleClearSelected = async () => {
    try {
        await ElMessageBox.confirm(
            '确定要删除选中的商品吗？',
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        await cartStore.clearSelected()
    } catch {
        // 用户取消删除
    }
}

// 结算
const handleCheckout = async () => {
    if (cartStore.selectedCount === 0) {
        ElMessage.warning('请选择要结算的商品')
        return
    }

    try {
        checkingOut.value = true

        // 重新获取用户积分，确保积分信息最新
        await userStore.initUserState()

        if (userStore.points < cartStore.totalPoints) {
            ElMessage.error('积分不足，无法结算')
            return
        }

        const selectedItems = cartStore.getSelectedItems()

        const orderId = await createOrder({
            userId: userStore.userId,
            items: selectedItems.map(item => ({ 
                productId: item.productId, 
                quantity: item.quantity, 
            }))
        })

        ElMessage.success('结算成功！')
        
        // 从购物车中移除已结算的商品
        await cartStore.clearSelected()

        // 跳转到订单详情页面
        router.push(`/orders/${orderId}`)

    } catch (error) {
        console.error('结算失败:', error)
        ElMessage.error('结算失败，请重试')
    } finally {
        checkingOut.value = false
    }
}
</script>

<style scoped>
.cart {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.loading-spinner {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
}

.cart-header {
    text-align: center;
    margin-bottom: 30px;
}

.cart-header h1 {
    color: #333;
    margin-bottom: 10px;
    font-size: 28px;
    font-weight: 600;
}

.cart-header p {
    color: #666;
    font-size: 16px;
}

.cart-content {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 20px;
}

.cart-list {
    margin-bottom: 20px;
}

.cart-header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.cart-items {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.cart-item {
    display: grid;
    grid-template-columns: auto 80px 1fr auto auto auto;
    gap: 15px;
    align-items: center;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    transition: background-color 0.3s;
}

.cart-item:hover {
    background-color: #f8f9fa;
}

.item-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
}

.item-info {
    flex: 1;
}

.item-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.item-points {
    font-size: 14px;
    color: #e6a23c;
    font-weight: 500;
}

.item-quantity {
    display: flex;
    align-items: center;
}

.item-total {
    text-align: right;
}

.total-points {
    font-size: 16px;
    font-weight: 600;
    color: #e6a23c;
}

.item-actions {
    display: flex;
    gap: 10px;
}

.cart-summary {
    position: sticky;
    top: 20px;
    height: fit-content;
}

.summary-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.summary-info {
    text-align: center;
}

.summary-info p {
    margin: 5px 0;
    color: #666;
}

.summary-info .total-points {
    font-size: 20px;
    font-weight: 600;
    color: #e6a23c;
}

.summary-actions {
    width: 100%;
}

.summary-actions .el-button {
    width: 100%;
    height: 50px;
    font-size: 16px;
    font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .cart-content {
        grid-template-columns: 1fr;
    }

    .cart-item {
        grid-template-columns: auto 60px 1fr;
        grid-template-rows: auto auto;
        gap: 10px;
    }

    .item-image {
        width: 60px;
        height: 60px;
    }

    .item-quantity,
    .item-total,
    .item-actions {
        grid-column: 1 / -1;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}
</style>
